package com.yubest.servletjsp.util;

import java.sql.*;
import java.util.Properties;

public class DbUtil {

    private DbUtil() {}

    private volatile static boolean isDriverLoaded = false;

    public static synchronized Connection getConnection() {
        try {
            Properties properties = ConfigUtil.read();

            if (!isDriverLoaded) {
                String driver = properties.getProperty("db.driver");
                Class.forName(driver);
                isDriverLoaded = true;
            }

            String url = properties.getProperty("db.url");
            String username = properties.getProperty("db.username");
            String password = properties.getProperty("db.password");

            return DriverManager.getConnection(url,username,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void close(Object ... args) {
        for (Object arg : args) {
            try {
                if (arg instanceof Connection) {
                    ((Connection) arg).close();
                } else if (arg instanceof PreparedStatement) {
                    ((PreparedStatement) arg).close();
                } else if (arg instanceof ResultSet) {
                    ((ResultSet) arg).close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
